/** @Date 下午6:43:18
  * @version 1.0.0
  * @author shangyd
  * Copyright (c) 2015
  */
package com.sdw.soft.test.zookeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MonitorCenter implements Watcher{

	private static final Logger logger = LoggerFactory.getLogger(MonitorCenter.class);
	
	private ZooKeeper zk = null;
	private CountDownLatch countdown = new CountDownLatch(1);
	private static final int TIMEOUT = 5000;
	private static final String PATH = "/sonicery";
	
	public MonitorCenter(String hosts){
		try {
			zk = new ZooKeeper(hosts, TIMEOUT, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					if(event.getState().SyncConnected == Event.KeeperState.SyncConnected){
						countdown.countDown();
					}
				}
			});
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(e.getMessage(),e);
		}
	}
	
	
	public void updateOrAdd(String path,String data) throws Exception{
		countdown.await();
		Stat stat = zk.exists(path, false);
		if(stat == null){
			zk.create(path, data.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			logger.info("create path =[" + path + "] successfully!!!");
		}else{
			zk.setData(path, data.getBytes(), -1);
			logger.info("set path [" + path + "] data successfully!!!");
		}
	}
	
	public String readData() throws Exception{
		return new String(zk.getData(PATH, this, null));
	}


	@Override
	public void process(WatchedEvent event) {
		try {
			if(event.getType() == Event.EventType.NodeDataChanged){
				logger.info("updated the data :" + readData());
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getMessage(),e);
		}
	}
	
	public void close(){
		try {
			zk.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
			logger.info(e.getMessage(),e);
		}
	}
	
}
